package com.jcw.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcw.common.R;
import com.jcw.domain.User;
import com.jcw.service.UserService;
import com.jcw.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
* @author JCW
* @description 针对表【user(用户信息)】的数据库操作Service实现
* @createDate 2023-03-30 09:55:34
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private HttpSession session;

    @Override
    public R<String> login(Map map) {
        String code = map.get("code").toString();
        String phone = map.get("phone").toString();
        String s = session.getAttribute(phone).toString();
        if (code.equals(s)){
            User user = query().eq("phone", phone).one();
            if (BeanUtil.isEmpty(user)){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success("登录成功");
        }
        return R.error("登录失败");
    }

    @Override
    public R<String> sendMsg(User user) {
        String code = RandomUtil.randomNumbers(6);
        log.info("你的验证码是：[{}]",code);
        session.setAttribute(user.getPhone(),code);
        return R.success(code);
    }

    @Override
    public R<String> loginout() {
        session.removeAttribute("user");
        return R.success("退出登录");
    }
}




